package engine.logic
{
	import flash.utils.getTimer;
	
	import newx.com.config.StaticIni;

	public class ChatFilterLogic
	{
		private var _filterList	:	Array	=	[];
		private var _leng			:	int		=	0;
		
		public function ChatFilterLogic()
		{
			_filterList	=	StaticIni.getIniVar("filter_list","data").split(",");
			_leng		=	_filterList.length;
		}
		
		private static var _self			:	ChatFilterLogic;
		public static function getInstance():ChatFilterLogic
		{
			if(_self == null)
			{
				_self	=	new ChatFilterLogic();
				
			}
			return _self;
		}
		
		public function filter(value : String) : String
		{
			var msg			:	String	=	value;
			var leng 		:	int		=	msg.length;
			var filters 	:	Array	=	[];
			if(value=="") return msg;
			for(var i : int = 0; i < leng; i++)
			{
				filters	=	getFilters(msg.charAt(i));
				if(null	==	filters)
				{
					continue;
				}else
				{//找到了
//					filters.sort(sortLeng);
					for(var j : int = 0; j < filters.length; j++)
					{
						if(leng >= filters[j].length && msg.indexOf(filters[j]) > -1)
						{
							var t : String = "";
							for(var k : int = 0; k < filters[j].length; k++)
							{
								t += "*";
							}
							msg = msg.replace(filters[j], t);
				//			i += filters[j].length;
							i --;
							break;
						}
					}
					
				}
			}
			return msg;
		}
//		
//		private function sortLeng(a : String, b : String):int
//		{
//			if(a.length	> b.length) return -1;
//			if(a.length	== 	b.length) return 0;
//			return 1;
//		}
		
		
		/**
		 *	查找屏蔽串 
		 * @param key		关键字
		 * @return 			位置
		 * 
		 */
		private function getFilters(key : String):Array
		{
			if(key == "*") return null;
			
			var front	:	int	=	0; 　　
			var end		: 	int	=	_leng - 1; 　　
			var mid		:	int	=	(front+end)/2; 　
			
			var chat	:	String;
			while((chat = _filterList[mid].charAt(0)) != key && front < end) 　　
			{ 　　
//				chat	=	_filterList[mid].charAt(0)
				if(chat < key)front 	= mid + 1; 　　
				if(chat > key)end		= mid - 1; 　　
				mid = (front + end) / 2; 　　
			}
			if(chat != key)
			{//没找到
				return null;
			}else
			{//找到了，获得区间
				var i : int	=	mid;
				for(i; i >=0 ;i--)
				{
					if(_filterList[i].charAt(0) < chat)
					{
						break;
					}
				}
				
				var j : int = 	mid;
				for(j; j < _leng ;j++)
				{
					if(_filterList[j].charAt(0) > chat)
					{
						break;
					}
				}
				return _filterList.slice(i + 1, j);
			}
		}
	}
}